package com.wxlgroup.springboot.controller;
import com.wxlgroup.springboot.commons.Response;
import com.wxlgroup.springboot.dao.DepartmentDao;
import com.wxlgroup.springboot.dao.UserDao;
import com.wxlgroup.springboot.entity.Department;
import com.wxlgroup.springboot.entity.User;
import com.wxlgroup.springboot.service.DepartmentService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/department")
public class DepartmentController {

    @Resource
    private DepartmentService departmentService;

    @Resource
    private UserDao userDao;

    @Resource
    private DepartmentDao departmentDao;




    @GetMapping("/page")
    public Response pages(
            String departmentName,
            int pageNumber,
            int pageSize){
        Object o = departmentService.queryAllDepartments(departmentName, pageNumber, pageSize);
        return new Response("200",o,"分页查询成功");
    }

    @GetMapping("/getUsers")
    public Response getUsers(){
        List<User> users = userDao.queryAll();
        List<String> usernames=new ArrayList<>();
        for (User user : users) {
            usernames.add(user.getUsername());
        }
        return new Response("200",usernames,"所有用户已返回");
    }


    //增加部门
    @PostMapping("/insert")
    @Transactional
    public Response insertDepartment(@RequestBody Department department){
        Integer flag = departmentDao.queryDepartmentIdByName(department.getDepartmentName());
        if(flag!=null){
            return new Response("500",null,"部门已存在，无法新增");
        }else {
            User user = userDao.findUserByUsername(department.getDepartmentCharger());
            department.setDepartmentHeadId(user.getId());
            departmentDao.insertDepartment(department);
            return new Response("200",null,"新增成功");
        }
    }


    @DeleteMapping("/delete/{departmentId}")
    public Response deleteDepartment(@PathVariable int departmentId){
        departmentDao.deleteDepartmentById(departmentId);
        return new Response("200",null,"删除成功");
    }



    @PostMapping("/update")
    public Response updateDepartment(@RequestBody Department department){
        User user = userDao.findUserByUsername(department.getDepartmentCharger());
        department.setDepartmentHeadId(user.getId());
        int i = departmentService.updateDepartmentById(department);
        if(i>0){
            return new Response("200",null,"修改成功");
        }else {
            return new Response("500",null,"修改失败");
        }
    }


    @GetMapping("/getDepartments")
    public Response getDepartments(){
        List<String> strings = departmentDao.queryAllDepartmentNames();
        if(strings!=null){
            return new Response("200",strings,"查询成功");
        }else {
            return new Response("500",null,"查询失败");
        }
    }
}
